//
//  SEGActivityCollectUploadViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/4.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGActivityCollectUploadViewController.h"
#import "SEGActivityCollectUploadView.h"
#import "SEGActivityCollectBrowseImageViewController.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import "SEGActivityCollectUploadViewModel.h"

@interface SEGActivityCollectUploadViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, SEGActivityAddPicDelegate, SEGImagePickerManagerDelegate>

/**
 上传界面
 */
@property (nonatomic, strong)SEGActivityCollectUploadView *uploadView;

/**
 是否显示按钮
 */
@property (nonatomic, strong)UIButton *showButton;



/** 相机, 相册 */
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

@property (nonatomic, strong) SEGActivityCollectUploadViewModel *viewModel;

@end

@implementation SEGActivityCollectUploadViewController

- (instancetype)initWithActId:(NSString *)actId isReview:(BOOL)isReview {
    if (self = [super init]) {
        self.viewModel = [[SEGActivityCollectUploadViewModel alloc] initWithActId:actId isReview:isReview];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //刷新界面
    [self.uploadView setPicArray:self.viewModel.savePicArray urlArray:self.viewModel.saveUrlArray];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColor_bg;
    self.title = @"发布";
    //返回
    [self showCustomNavigationBackButton];
    //确定
    [self showCustomNavigationRightButtonWithTitle:@"确定" image:nil hightlightImage:nil color:kColor_T];
    
    
    
    self.uploadView = [[SEGActivityCollectUploadView alloc] init];
    self.uploadView.delegate = self;
    [self.view addSubview:self.uploadView];
    [self.uploadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
    }];
    
    if (self.viewModel.isReview) {//活动开启留言板才有展示选项
        UIButton *showButton = [[UIButton alloc] init];
        [showButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select_nor")] forState:UIControlStateNormal];
        [showButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")] forState:UIControlStateSelected];
        [showButton addTarget:self action:@selector(showButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:showButton];
        [showButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(11);
            make.top.equalTo(self.uploadView.mas_bottom).offset(11);
            make.width.height.mas_equalTo(24.0);
        }];
        showButton.selected = YES;//默认选中
        self.showButton = showButton;
        
        UILabel *lable = [[UILabel alloc] init];
        lable.font = kFont_13;
        lable.textColor = kColor_1;
        lable.text = @"展示上传的图片到邻居说";
        [self.view addSubview:lable];
        [lable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(showButton.mas_right).with.offset(1);
            make.centerY.equalTo(showButton);
        }];
    }
}

- (void)showButtonPressed
{
    self.showButton.selected = !self.showButton.selected;
}

//右侧按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    [self.view endEditing:YES];
    NSString *show = [NSString stringWithFormat:@"%d",self.showButton.selected];
    RACTuple *tup = RACTuplePack(self.uploadView.describeView.text,show);
    
    [[self.viewModel.upLoadImagesAndSaveCommentCommand execute:tup] subscribeNext:^(id  _Nullable x) {
        if ([x isKindOfClass:[NSNumber class]]) {
            NSNumber *isShow = x;
            if (isShow.boolValue) {
                [SVProgressHUD show];
            }else {
                [SVProgressHUD dismiss];
            }
        }
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        if (error.code == 1001) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } completed:^{
        [SVProgressHUD dismiss];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SEGAlertView showTmepMessageWithMessage:@"作品提交成功"];
        });
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

#pragma mark - SEGActivityAddPicDelegate代理方法 选择图片弹出视图
- (void)addPicAction
{
    [self.view endEditing:YES];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择",@"相机",nil];
    [actionSheet showFromTabBar:self.navigationController.tabBarController.tabBar];
}

- (void)removePicAtIndex:(NSUInteger)index
{
    [self.viewModel.savePicArray removeObjectAtIndex:index];
    if (self.viewModel.saveUrlArray.count > index) {//编辑的时候 由于最初的时候是图片和URL一一对应的 所以要一起删除
        [self.viewModel.saveUrlArray removeObjectAtIndex:index];
    }
    [self.uploadView setPicArray:self.viewModel.savePicArray urlArray:self.viewModel.saveUrlArray];
}

- (void)tapPicAtIndex:(NSUInteger)index
{
    SEGActivityCollectBrowseImageViewController *vc = [[SEGActivityCollectBrowseImageViewController alloc] init];
    vc.imageArray = self.viewModel.savePicArray;
    vc.currentIndex = index;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UIActionSheetDelegate代理方法 选择图片弹出视图处理
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0: //从手机相册选择
        {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
            self.imagePicker.allowsEditing = NO;
            self.imagePicker.maxImagesCount = (int)SEGActivityPhotoMax - (int)[self.viewModel.savePicArray count];
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
            break;
        }
        case 1: //相机
        {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
            self.imagePicker.allowsEditing = NO;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
            break;
        }
        default:
            break;
    }
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager
        didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                        assets:(NSArray<PHAsset *> *)assets
         isSelectOriginalPhoto:(BOOL)isSelect
{
    [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.viewModel.savePicArray addObject:obj];
        [self.uploadView setPicArray:self.viewModel.savePicArray urlArray:self.viewModel.saveUrlArray];
    }];
}



@end

